#!/usr/bin/env python
#go2_utils.py

go2_settings = {"verbose":True, "modified":False, "filepath":'', "wintitle":"[Untitled]"}

from xml.etree.cElementTree import ElementTree, Element, SubElement

# logging function to print to console #

def info(text):
	if(go2_settings["verbose"]):
		print text

# file i/o and xml to treemodel transformation #

def save_file(treestore, fpath):
	root = Element("root")
	
	for row in treestore:
		write_row(row, root)
		
	ElementTree(root).write(fpath)
	
	
def write_row(row, elemParent):
	#row is a gtk.TreeModelRow, elemParent is a TreeElement.Element
	elemSub = SubElement(elemParent, "node")
	elemSub.text = row[0]
	for subrow in row.iterchildren():
		write_row(subrow, elemSub)

def read_file(fpath, treestore):
	#read xml file format, convert to treemodel and return
	
	tree = ElementTree( file=fpath)
	root = tree.getroot()

	#iterate over 
	for node in root:
		#top level items, add then read for children
		iter = treestore.append(None)
		treestore.set_value(iter, 0, node.text)
		read_row(iter, treestore, node)
	
	return(treestore)
	
def read_row(iter, treestore, elemParent):
	#iter and elemParent are matching tree elements in a treestore and 
	#ElementTree respectively
	for child in elemParent:
		subiter = treestore.append(iter)
		treestore.set_value(subiter, 0, child.text)
		read_row(subiter, treestore, child)


